package com.sairobo.admin.modules.ueditor.upload;

import com.sairobo.admin.config.UEditorConfig;
import com.sairobo.admin.modules.ueditor.define.AppInfo;
import com.sairobo.admin.modules.ueditor.define.BaseState;
import com.sairobo.admin.modules.ueditor.define.State;
import com.sairobo.base.common.utils.SpringUtil;
import com.sairobo.base.modules.cloud.OSSFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class StorageManager {
	public static final int BUFFER_SIZE = 8192;

	public StorageManager() {
	}

	public static State saveBinaryFile(byte[] data, String path) {
		File file = new File(path);

		State state = valid(file);

		if (!state.isSuccess()) {
			return state;
		}

		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			bos.write(data);
			bos.flush();
			bos.close();
		} catch (IOException ioe) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}

		state = new BaseState(true, file.getAbsolutePath());
		state.putInfo( "size", data.length );
		state.putInfo( "title", file.getName() );
		return state;
	}

	public static State saveFileByInputStream(InputStream is, String path,
			long maxSize) {
		State state = null;

		File tmpFile = getTmpFile();

		byte[] dataBuf = new byte[ 2048 ];
		BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();

			if (tmpFile.length() > maxSize) {
				tmpFile.delete();
				return new BaseState(false, AppInfo.MAX_SIZE);
			}

			state = saveTmpFile(tmpFile, path);

			if (!state.isSuccess()) {
				tmpFile.delete();
			}

			return state;
			
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	public static State saveFileByInputStream(InputStream is, String path) {
		State state = null;

		File tmpFile = getTmpFile();

		byte[] dataBuf = new byte[ 2048 ];
		BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();

			state = saveTmpFile(tmpFile, path);

			if (!state.isSuccess()) {
				tmpFile.delete();
			}

			return state;
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static File getTmpFile() {
		File tmpDir = FileUtils.getTempDirectory();
		String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
		return new File(tmpDir, tmpFileName);
	}

	private static State saveTmpFile(File tmpFile, String path) {
		State state = null;
		File targetFile = new File(path);

		if (targetFile.canWrite()) {
			return new BaseState(false, AppInfo.PERMISSION_DENIED);
		}
        state = new BaseState(true);
        UEditorConfig uec = SpringUtil.getBean(UEditorConfig.class);
        //上传到七牛还是本地
        String uploadTo = uec.getUploadTo();
        state.putInfo("uploadTo",uploadTo);
        if(StringUtils.isNotEmpty(uploadTo) && UEditorConfig.QINIU.equalsIgnoreCase(uploadTo)){
            //7牛上传文件
            try {
                //tmpFile转化为MultipartFile
                FileInputStream inputStream = new FileInputStream(tmpFile);
                MultipartFile multipartFile = new MockMultipartFile(tmpFile.getName(), inputStream);

                //调用7牛上传接口
                String suffix = path.substring(path.lastIndexOf("."));
                String url = OSSFactory.build().uploadSuffix(multipartFile.getBytes(), suffix);
                state.putInfo( "size", targetFile.length() );
                state.putInfo( "title", path.substring(path.lastIndexOf("/")+1));
                state.putInfo("url",url);
                return state;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                FileUtils.moveFile(tmpFile, targetFile);
            } catch (IOException e) {
                return new BaseState(false, AppInfo.IO_ERROR);
            }
            state.putInfo( "size", targetFile.length() );
            state.putInfo( "title", targetFile.getName() );
        }
        return state;
	}

	private static State valid(File file) {
		File parentPath = file.getParentFile();

		if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
			return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
		}

		if (!parentPath.canWrite()) {
			return new BaseState(false, AppInfo.PERMISSION_DENIED);
		}

		return new BaseState(true);
	}
}
